import Vue from 'vue'
import Router from 'vue-router'
import store from '../vuex'
import {clearvuex} from "../vuex/clear";
import {message,getLocalStorage,delLocalStorage} from '../common/util'

import IndexPage from '@/pages/index'
import LoginPage from '@/pages/login'
import SettingPage from '@/pages/setting'
import PasswordPage from '@/pages/password'
import SubscribeManagerPage from '@/pages/subscribeManager'
import AddSubscribePage from '@/pages/subscribeManager/addSubscribe'
import HolidayPartyListPage from '@/pages/subscribeManager/holidayPartyList'
import HolidayPartyDetailPage from '@/pages/subscribeManager/holidayPartyDetail'
import ToPayDepositPage from '@/pages/subscribeManager/toPayDeposit'
import SubscribeDetailPage from '@/pages/subscribeManager/subscribeDetail'
import DepositTermPage from '@/pages/subscribeManager/depositTerm'
import PresentManagerPage from '@/pages/presentManager'
import ChoosePresentPage from '@/pages/presentManager/choosePresent'
import SubmitPresentPage from '@/pages/presentManager/submitPresent'
import PresentedListPage from '@/pages/presentManager/presentedList'
import PresentDetailPage from '@/pages/presentManager/presentDetail'
import UnpayPresentedPage from '@/pages/presentManager/unpayPresented'
import TurnoverStatisticsPage from '@/pages/turnoverStatistics'

Vue.use(Router)

const router = new Router({
  //mode:'history',//网址没有了#号，hBuilder打包成APP不能使用，需要注释
  base: '/stock/',
  routes: [
    {
      path: '/login',
      name: '登录',
      component: LoginPage
    },
    {
      path: '/password',
      name: '重置密码',
      component: PasswordPage
    },
    {
      path: '/',
      name: '主页',
      component: IndexPage,
      meta:{requireAuth: true }
    },
    {
      path: '/setting',
      name: '设置',
      component: SettingPage,
      meta:{requireAuth: true }
    },
    {
      path: '/subscribeManager',
      name: '客户预订管理',
      component: SubscribeManagerPage,
      meta:{requireAuth: true, module:['subscribeManager_stock'] }
    },
    {
      path: '/addSubscribe/:subscribe',
      name: '增加预订',
      component: AddSubscribePage,
      meta:{requireAuth: true, module:['subscribeManager_stock'] }
    },
    {
      path: '/holidayPartyList',
      name: '节日/派对列表',
      component: HolidayPartyListPage,
      meta:{requireAuth: true, module:['subscribeManager_stock'] }
    },
    {
      path: '/holidayPartyDetail/:holidayPartyId',
      name: '节日/派对详情',
      component: HolidayPartyDetailPage,
      meta:{requireAuth: true, module:['subscribeManager_stock'] }
    },
    {
      path: '/toPayDeposit/:subscribeId',
      name: '订金支付',
      component: ToPayDepositPage,
      meta:{requireAuth: true, module:['subscribeManager_stock'] }
    },
    {
      path: '/subscribeDetail/:subscribeId/:type',
      name: '预订详情',
      component: SubscribeDetailPage,
      meta:{requireAuth: true, module:['subscribeManager_stock'] }
    },
    {
      path: '/depositTerm',
      name: '预订协议',
      component: DepositTermPage,
      meta:{requireAuth: true, module:['subscribeManager_stock'] }
    },
    {
      path: '/presentManager',
      name: '当前可赠送列表',
      component: PresentManagerPage,
      meta:{requireAuth: true, module:['presentManager_stock'] }
    },
    {
      path: '/choosePresent/:type/:orderId',
      name: '选择要赠送商品',
      component: ChoosePresentPage,
      meta:{requireAuth: true, module:['presentManager_stock'] }
    },
    {
      path: '/submitPresent/:type/:orderId',
      name: '提交赠送',
      component: SubmitPresentPage,
      meta:{requireAuth: true, module:['presentManager_stock'] }
    },
    {
      path: '/presentedList',
      name: '赠送酒水查询',
      component: PresentedListPage,
      meta:{requireAuth: true, module:['presentManager_stock'] }
    },
    {
      path: '/presentDetail/:presentId',
      name: '赠送酒水详情',
      component: PresentDetailPage,
      meta:{requireAuth: true, module:['presentManager_stock'] }
    },
    {
      path: '/unpayPresented',
      name: '未结账赠送查询',
      component: UnpayPresentedPage,
      meta:{requireAuth: true, module:['presentManager_stock'] }
    },
    {
      path: '/turnoverStatistics',
      name: '营业额统计',
      component: TurnoverStatisticsPage,
      meta:{requireAuth: true, module:['turnoverStatistics_stock'] }
    }
  ]
})

router.beforeEach((to, from, next) => {//验证
  //console.log(to, from)
  setTimeout(()=>{
    store.commit('updateLoadingStatus', {isLoading: true})

    function requireAuth(){
      return new Promise(function(resolve, reject){
        if(to.meta.requireAuth) resolve()
        else reject({path:'',mess:'无需授权登录的页面'})
      })
    }
    function loginOrNot(){
      return new Promise(function(resolve, reject){
        //console.log('router index:',sessionStorage.getItem('index'))
        if (getLocalStorage('token_stock_index' + sessionStorage.getItem('index')) && getLocalStorage('userId_stock_index' + sessionStorage.getItem('index'))) resolve()
        else reject({path:'/login',mess:'登陆信息失效，请重新登陆，或关闭页面后重新进入系统'})
      })
    }
    function getAuthority(){
      return new Promise(function(resolve, reject){
        if(JSON.stringify(store.getters.getAuthority) != '{}')
          resolve()
        else
          store.dispatch('fetchAuthority',{callback:(status)=>{
              if(status == 'success'){
                resolve()
              }else if(status == 'error'){
                reject({path:'/login',mess:'用户未设置任何权限'})
              }
            }
          })
      })
    }
    function dispatchAuthority(){
      return new Promise(function(resolve, reject){
        let flag = false
        for(let authorityItem of store.getters.getAuthority.h5_stockHelper){//一级权限（模块权限）的判断
          if(typeof authorityItem == 'object') {
            for(var key in authorityItem) {
              if(to.meta.module)
                for(let moduleItem of to.meta.module){
                  if(key == moduleItem) flag = true
                }
            }
          } else if(typeof authorityItem == 'string') {
            if(to.meta.module)
              for(let moduleItem of to.meta.module){
                if(authorityItem == moduleItem) flag = true
              }
          }
        }
        if(flag || to.name == '主页' || to.name == '设置'){
          resolve()
        }else{
          reject({path:'/',mess:'没有权限查看该页面'})
        }
      })
    }

    requireAuth().then((mess)=>{
      return loginOrNot()
    }).then((mess)=>{
      return getAuthority()
    }).then((mess)=>{
      return dispatchAuthority()
    }).then((mess)=>{
      next()
    }).catch((data)=>{
      console.log(data.mess)
      if(data.path == '/login'){
        delLocalStorage('token_stock_index' + sessionStorage.getItem('index'))
        delLocalStorage('userId_stock_index' + sessionStorage.getItem('index'))
        clearvuex()
        store.commit('updateLoadingStatus', {isLoading: false})
        message({message:data.mess,type:'error'})
        next({path:'/login'})
      }else{
        if(data.path == '')next()
        else next(data.path)
      }
    })
  },1)
});

router.afterEach((to, from) => {//验证
  /*
    store.commit('updateLoadingStatus', {isLoading: false})
  */
  if(from.path == '/login'){
  }
});

export default router
